package com.System.LearnSystem;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import com.fasterxml.jackson.annotation.JsonIgnore;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

public class Token<T> {
	 // 生成安全的密钥
    private static final Key SECRET_KEY = (Key)Keys.secretKeyFor(SignatureAlgorithm.HS256);
    // 令牌有效期（毫秒）- 半小时
    private static final long EXPIRATION_TIME = 30 * 60 * 1000;
    
    private static String token = null;
    
    private T userinfo;
    
    
    public Token(T userinfo,String username,String role)//构造方法，用于根据用户名生成代码
    {
    	this.userinfo = userinfo;
    	Map<String, Object> claims = new HashMap<>();
        claims.put("role", role);
        token = generateToken(username,claims);
    }
    
 // 模拟黑名单存储，实际可替换为Redis等
    private static final Map<String, Long> revokedTokens = new ConcurrentHashMap<>(); 

    /**
     * 生成 JWT 令牌
     * @param username 用户名
     * @param claims 额外声明信息
     * @return 生成的 JWT 令牌
     */
    private static String generateToken(String username, Map<String, Object> claims) {
        if (claims == null) {
            claims = new HashMap<>();
        }      
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION_TIME);
        
        token =  Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith((java.security.Key) SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
        return token;
    	}
    /**
   	 * 验证 JWT 令牌
 	 * @param token JWT 令牌
 	 * @return 解析出的 Claims 对象
     */
    public static boolean checkToken(String token)
    {
    	try {									//解析代码
    			Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
    			return true;
        } catch (Exception e) {
            // 可根据具体异常类型进行处理
            System.err.println("令牌验证失败: " + e.getMessage());
            return false;
        }
    }
     // 从令牌中获取用户名
    @JsonIgnore
    public  String getUsernameFromToken() {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims != null ? claims.getSubject() : null;
    }
    
    public static void revokeToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                   .setSigningKey(SECRET_KEY)
                   .build()
                   .parseClaimsJws(token)
                   .getBody();
            Date expiration = claims.getExpiration();
            long remainingTime = expiration.getTime() - System.currentTimeMillis();
            if (remainingTime > 0) {
                revokedTokens.put(token, expiration.getTime());
            }
        } catch (Exception e) {
            // 处理令牌解析异常等情况
            e.printStackTrace();
        }
    }



    public String gettoken()
	{
		return token;
	}
    
	public T getUserinfo() {
		return userinfo;
	}


	public void setUserinfo(T userinfo) {
		this.userinfo = userinfo;
	}
	
	
}
